﻿using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Spark.Utility
{
    public static class HttpHelper
    {
        public static async Task<T> Post<T>(string url, string content)
        {
            using (var httpClient = new HttpClient())
            {
                var httpContent = new StringContent(content, Encoding.Default, "application/x-www-form-urlencoded");
                using (var httpResponseMessage = await httpClient.PostAsync(url, httpContent))
                {
                    if (httpResponseMessage.IsSuccessStatusCode)
                    {
                        var result = await httpResponseMessage.Content.ReadAsStringAsync();
                        return JsonConvert.DeserializeObject<T>(result);
                    }
                    else
                    {
                        return await Task.FromResult(default(T));
                    }
                }
            }
        }

        public static async Task<T> Get<T>(string url)
        {
            using (var httpClient = new HttpClient())
            {
                using (var httpResponseMessage = await httpClient.GetAsync(url))
                {
                    if (httpResponseMessage.IsSuccessStatusCode)
                    {
                        var result = await httpResponseMessage.Content.ReadAsStringAsync();
                        return JsonConvert.DeserializeObject<T>(result);
                    }
                    else
                    {
                        return await Task.FromResult(default(T));
                    }
                }
            }
        }
    }
}